import { Inject, Provide } from '@midwayjs/decorator';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
import { ICoolCache, Cache } from 'midwayjs-cool-core';

import { CreateCartDto, UpdateCartDto, CartPageDto } from '../dto/cart';

import { CustomerCartEntity } from '../entity/cart';
import { MallProductClothingEntity } from '../../mall/entity/productClothing';
import { MallProductClothingService } from '../../mall/service/productClothing';
import { MallProductEntity } from '../../mall/entity/product';
import { CustomerEntity } from '../entity/customer';

@Provide()
export class CustomerCartService {
  @Inject()
  mallProductClothingService: MallProductClothingService;

  @InjectEntityModel(CustomerEntity)
  customerEntity: Repository<CustomerEntity>;

  @InjectEntityModel(CustomerCartEntity)
  customerCartEntity: Repository<CustomerCartEntity>;

  @InjectEntityModel(MallProductEntity)
  mallProductEntity: Repository<MallProductEntity>;

  @InjectEntityModel(MallProductClothingEntity)
  mallProductClothingEntity: Repository<MallProductClothingEntity>;

  @Inject('cool:cache')
  coolCache: ICoolCache;

  /**
   * 事务：
   * - 添加到购物车
   * - 根据 productId 查询商品信息（title、poster、sale）
   * - 根据 skuId 查询 SKU 信息
   * - 计算总价
   */
  async add(cartItem: CreateCartDto) {
    const { id } = await this.customerCartEntity.save(cartItem);
    const data = await this.customerCartEntity
      .createQueryBuilder('c')
      .select(['c.id', 'c.productId', 'c.count'])
      .where('id = :id', { id })
      .getOne();
    const sku = await this.mallProductClothingEntity
      .createQueryBuilder('s')
      .select(['s.poster', 's.color', 's.size', 's.price'])
      .where('id = :id', { id: cartItem.skuId })
      .getOne();
    return Object.assign(data, sku, { total: data.count * sku.price });
  }

  /**
   * 封装数据：
   * - 根据 productId 查询 SPU 信息
   * - 根据 skuId 查询 SKU 信息
   * - 新增列 total(price * count)
   */
  @Cache(10)
  async info(id: number) {
    const cart = await this.customerCartEntity
      .createQueryBuilder('c')
      .select(['c.id', 'c.skuId', 'c.productId', 'c.count'])
      .where('id = :id', { id })
      .getOne();
    const product = await this.mallProductEntity
      .createQueryBuilder('p')
      .select(['p.title', 'p.poster', 'p.sale', 'p.categoryId', 'p.keyword'])
      .where('id = :id', { id: cart.productId })
      .getOne();
    const sku = await this.mallProductClothingEntity
      .createQueryBuilder('s')
      .select(['s.poster', 's.color', 's.size', 's.price'])
      .where('id = :id', { id: cart.skuId })
      .getOne();
    return Object.assign({}, cart, product, {
      sku,
      total: cart.count * sku.price,
    });
  }

  /**
   * cartIds：查找 customer 的 cart => 调用多次 info() 返回数据
   * 但如何处理 start、limit ？
   */
  @Cache(10)
  async page(pageOp: CartPageDto) {
    const count = await this.customerCartEntity.count({
      customerId: pageOp.customerId,
    });
    const data = await this.customerCartEntity.find({
      where: { customerId: pageOp.customerId },
      skip: pageOp.start,
      take: pageOp.limit,
      order: { createTime: 'DESC' },
    });
    return { count, data };
  }

  async delete(id: number) {}

  async update(cartItem: UpdateCartDto) {}
}
